package cn.zhuangcloud.newversion.login;

import cn.zhuangcloud.newversion.common.enums.RetCodeEnum;
import cn.zhuangcloud.newversion.common.enums.en.RetMessageEnum;
import cn.zhuangcloud.newversion.common.kit.PasswordKit;
import cn.zhuangcloud.newversion.common.kit.TokenKit;
import cn.zhuangcloud.newversion.common.model.Users;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginService {

    public static final LoginService me = new LoginService();
    private static final Users userDao = new Users().dao();
    private static final Logger log = LoggerFactory.getLogger(LoginService.class);

    public Ret login(String username, String password) {

        System.out.println(username + password);

        Users user = userDao.findFirst(userDao.getSqlPara("user.findByUsername", username));
        if (null == user) {
            return Ret.by("status", false).set("code", RetCodeEnum.WRONG_PASSWORD).set("message", RetMessageEnum.WRONG_PASSWORD);
        }

        if (!user.getPwd().equals(PasswordKit.hash(password, user.getSalt()))) {
            return Ret.by("status", false).set("code", RetCodeEnum.WRONG_PASSWORD).set("message", RetMessageEnum.WRONG_PASSWORD);
        }


        String token = StrKit.getRandomUUID();
        TokenKit.setToken(user.getUsername(), token);

        log.info("{} login with token {}", username, token);
        return Ret.by("status", true).set("code", RetCodeEnum.LOGIN_SUCCESS).set("message", RetMessageEnum.LOGIN_SUCCESS).set("token", token);

    }

}
